
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rfid/page/borrow_result_page.dart';
import 'package:rfid/page/help_page.dart';
import 'package:rfid/util/toast_util.dart';
import 'package:rfid/widget/auth_dialog.dart';
import '../entity/book_entity.dart';
import '../entity/current_task_entity.dart';
import '../event/lock_state_event.dart';
import '../main.dart';
import '../util/timer_manager.dart';
import '../widget/device_name_widget.dart';
import '../widget/focus_killer.dart';


class BookDetail extends StatefulWidget {
  const BookDetail({Key? key}) : super(key: key);

  @override
  State<BookDetail> createState() => _BookDetailState();
}

class _BookDetailState extends State<BookDetail> {

  late BookEntity bookEntity;

  String? _ant;
  String? _addr;
  String? _readerIp;
  String? _lock;

  StreamSubscription? lockSubscription;


  @override
  initState() {
    super.initState();
    bookEntity = Get.arguments;

    if(settingEntity.reader != null && settingEntity.reader!.isNotEmpty){
      var doors = settingEntity.reader!.where((element) => element.doorNo == bookEntity.doorNo);
      if(doors.isNotEmpty){
        _ant = doors.first.ant;
        _addr = doors.first.addr;
        _readerIp = doors.first.readerIp;
        _lock = doors.first.lock;
      }
    }else{
      toastWarn("未配置格口");
    }

    lockSubscription = eventFactory.on<LockStateEvent>().listen((event) {
      if(event.state == 1 && currentTask.uid != null){
        Get.to(() => const BorrowResult());
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.normal,(){
        Get.until((route) => route.isFirst);
      });
    });

  }

  @override
  void dispose() {

    lockSubscription?.cancel();
    lockSubscription = null;
    super.dispose();
  }


  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(),
          InkWell(
            onTap: (){
              Get.to(()=> const Help());
            },
            child:  Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                focusKiller(),
                Icon(Icons.help,color: Colors.white,size: 20.sp,),
                Text(" 帮助",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
              ],
            ),
          )

        ],
      ),
    );
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top: 20.h,left: 20.w,right: 20.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                Get.back();
              },
              child: _image("assets/images/back.png",60.w,23.h),
            ),
            _image("assets/images/book_detail_title.png",90.w,21.h),
            Obx(() => Text("${timer.normalTime.value}s",style: TextStyle(color: Colors.white,fontSize: 12.sp),))
          ],
        )
    );
  }

  _booksContainer(){
    return Container(
      decoration:BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      margin: EdgeInsets.only(left: 20.w,right: 20.w,top: 20.h),
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 6.w,bottom: 6.w),
      width: double.infinity,
      height: 520.h,
      child: Stack(
        children: [
          Positioned(
            top: 10.h,
            left: 0.w,
            child:  bookEntity.cover!= null?Image.memory(base64Decode(bookEntity.cover??''),
              gaplessPlayback: true,//防止重绘
              width: 70.w,
              height: 89.h,
              fit: BoxFit.cover,
            ):Image.asset("assets/images/default.jpg",height: 89.h, width: 70.w, fit: BoxFit.fill,),
          ),
          Positioned(
            top: 30.h,
            left: 100.w,
            child: Text(bookEntity.mainTitle??'',style: TextStyle(fontSize: 12.sp,color: Colors.black,fontWeight: FontWeight.w500),),
          ),
          Positioned(
            top: 65.h,
            left: 100.w,
            child: Text(bookEntity.author??'',style: TextStyle(fontSize: 8.sp,color: Colors.black),),
          ),
          Positioned(
            top: 79.h,
            left: 100.w,
            child: Text(bookEntity.publisher??'',style: TextStyle(fontSize: 8.sp,color: Colors.black),),
          ),
          Positioned(
            top: 93.h,
            left: 100.w,
            child: Text(bookEntity.subject??'',style: TextStyle(fontSize: 8.sp,color: Colors.black),),
          ),
          Positioned(
            top: 160.h,
            left: 0.w,
            child: Text('作品简介',style: TextStyle(fontSize: 12.sp,color: Colors.black,fontWeight: FontWeight.w500),),
          ),

          Positioned(
            top: 190.h,
            left: 0.w,
            child: SizedBox(
              width: 300.w,
              child: Text('${bookEntity.summary}',style: TextStyle(fontSize: 8.sp,color: Colors.black),maxLines: 10, overflow: TextOverflow.ellipsis,),
            )
          ),

          Positioned(
            top: 330.h,
            left: 0.w,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text('ISBN: ',style: TextStyle(fontSize: 12.sp,color: Colors.black,fontWeight: FontWeight.w500),),
                Text(bookEntity.isbn??'',style: TextStyle(fontSize: 8.sp,color: Colors.black),),
              ],
            )
          ),
          Positioned(
            top: 355.h,
            left: 0.w,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text('索书号: ',style: TextStyle(fontSize: 12.sp,color: Colors.black,fontWeight: FontWeight.w500),),
                Text(bookEntity.searchNo??'',style: TextStyle(fontSize: 8.sp,color: Colors.black),),
              ],
            )
          ),
          Positioned(
            top: 380.h,
            left: 0.w,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text('条码: ',style: TextStyle(fontSize: 12.sp,color: Colors.black,fontWeight: FontWeight.w500),),
                Text(bookEntity.no??'',style: TextStyle(fontSize: 8.sp,color: Colors.black),),
              ],
            )
          ),
          Positioned(
            top: 400.h,
            left: 0.w,
            child: InkWell(
              onTap: (){
                currentTask.task = Task.borrowWithDoor;
                currentTask.readerIp = _readerIp;
                currentTask.addr = _addr;
                currentTask.lock = _lock;
                currentTask.ant = _ant;
                currentTask.doorNo = bookEntity.doorNo;
                currentTask.needCheckCount = true;

                AuthDialog().authTypeDialog(callback: (){
                  timer.startCountDown(CountDownMode.normal,(){
                    if(Get.isDialogOpen != null && Get.isDialogOpen!){
                      Get.back();
                    }
                  }, reset: false);
                });
              },
              child: _image("assets/images/to_borrow.png", 300.w, 134.h),
            )
          ),
        ],
      )
    );
  }

  _image(name,width, height){
    return Image.asset(name,height: height, width: width, fit: BoxFit.fill,);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            _appBar(),
            _title(),
            _booksContainer(),

          ],
        ),
      ),
    );
  }
}

